package com.market.category.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.market.category.dao.CategoryDao;
import com.market.category.domain.CategoryCommand;
import com.market.category.validator.CategoryValidator;

@Controller
public class CateWriteController {
	@Autowired
	private CategoryDao categoryDao;	
	
	@ModelAttribute("command")
	public CategoryCommand initCommand(){
		return new CategoryCommand();
	}	
	
	@RequestMapping(value="/categoryWrite.do",method=RequestMethod.GET)
	public ModelAndView form(@RequestParam("pageNum") int pageNum,
			@RequestParam("searchMarket") String keyWord) {
		ModelAndView mav = new ModelAndView();
		
		mav.setViewName("categoryWrite");
		mav.addObject("pageNum", pageNum);
		mav.addObject("searchMarket", keyWord);
		
		return mav;
	}
	
	@RequestMapping(value="/categoryWrite.do",method=RequestMethod.POST)
	public String submit(@ModelAttribute("command")CategoryCommand categoryCommand,
			BindingResult result,
			@RequestParam("pageNum") int pageNum,
			@RequestParam("searchMarket") String keyWord){
		
		new CategoryValidator().validate(categoryCommand, result);

		if(result.hasErrors()){
			return "categoryWrite";
		}
		
		try{			
			categoryDao.insert(categoryCommand);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return "redirect:/categoryList.do?pageNum="+pageNum+"&searchMarket="+keyWord;
	}
}
